<div class="row animate fadeIn">
    <form id="edit_rates_form" class="form-horizontal"  method="post">
      <?php foreach ($rates_data as $rates) { ?>
        <input type="hidden" name="hidden_rate_id" id="edit_rate_id" value="<?php echo $rates->rate_id ;?>">
        <div class="ibox-title" style="border:none;"><h5 style="color: #00afef"><i>Edit Rates</i></h5>
            <div class="ibox-tools">    
                <button  id="sads" class="btn btn-sm btn-primary save-btn-tab">Save</button>
                <a id = "cancel_edit" class="btn btn-sm btn-outline btn-info cancel-btn-tab">Cancel</a>
            </div>
        </div>
        <div class="ibox-content">
           <div class="form-group">
            <label class="col-lg-3 control-label">Charge List</label>
            <div class="col-lg-4">
               <input type="text" name="chgid" class="form-control" readonly value="<?php echo $rates->list_name ;?>">
            </div>
          </div>   
          <div class="form-group">
              <label class="col-lg-3 control-label">Rate Name</label>
            <div class="col-lg-4">
              <input type="text" name="edit_rate_name" class="form-control" value="<?php echo $rates->rate_name ;?>">
            </div>
          </div>
          <div class="form-group">
              <label class="col-lg-3 control-label">Description</label>
            <div class="col-lg-4">
              <input type="text" name="edit_rate_description" class="form-control" value="<?php echo $rates->description ;?>">
            </div>
          </div>
          <div class="form-group">
              <label class="col-lg-3 control-label">Enable</label>
            <div class="col-lg-4">
              <input type="checkbox" value="ok" name="edit_ena_rate" id="edit_rate_ena" class="i-checks" <?php echo($rates->enable_flag == 'Y' ? 'checked' : '' ); ?> >
            </div>
          </div>
        </div>
        <?php } ?>
    </form>
<!--  -->
        <div id="edit_rate_sched" class="ibox-content">
            <h3 style="color: #00afef">Update Rate Schedule</h3>
              <form  id="edit_rate_list_form" class="form-inline">
                <input type="hidden" name="edit_hidden_rate_id" id="edit_s_rate_id">
            </br>
              <table id="pgTable"class="table table-bordered" style="width:100%;">

                <thead>
                    <tr>
                      <th style="">Charge Element</th>
                      <th>Description</th>
                      <th style="width:130px;text-align:right;">Usage Quantity</th>
                      <th style="width:100px;text-align:right;">Rate</th>
                      <th style="width:120px;text-align:right;">MIN/DEF MIN</th>
                      <th style="width:80px;">Action</th>
                    </tr>
                    <tr>
                      <td style="margin:0px;padding:0px;">
                          <select id="edit_r_chg_code" class="chosen-select" name="edit_r_chg_name">
                                <?php foreach($elements as $chg) { ?>
                                    <option value="<?php echo $chg->charge_code; ?>"> <?php echo $chg->charge_name; ?> </option>
                                <?php } ?>
                            </select>
                      </td>
                      <td style="margin:0px;padding:0px;">
                          <input style="width:100%;" type="text" id="" name="edit_r_desc" class="form-control-custom" value="Water Consumption">
                      </td>
                      <td style="margin:0px;padding:0px;">
                          <input style="width:100%;" type="text" id="" name="edit_r_usage" class="form-control-custom">
                      </td>
                      <td style="margin:0px;padding:0px;">
                          <input style="width:100%;" type="text" id="seq_num" name="edit_r_rate" class="form-control-custom">
                      </td>
                      <td style="margin:0px;padding:0px;">
                       
                      </td>
                      <td style="margin:0px;padding:0px;">
                          <button style="width:100%;" class="btn btn-white" id=""><i class="fa fa-plus success"></i></button>
                      </td>
                    </tr>      
                </thead>
              </form>
              
                
                <tbody id="tbl_ratesEdit" class="animate fadeIn">       

                </tbody>
              </table> 
        </div>
</div>
<script>
$(document).ready(function () {
    $('#edit_rates_form').data('serialize',$('#edit_rates_form').serialize());
    $(".chosen-select").chosen({width:"100%;"});
    var setter = 0;
    var current_usage;
    var current_rate;
    var min_box; var min_box_df;
    var min_usg = 0;
    var r_id = $('#edit_rate_id').val();
    $('#edit_s_rate_id').val(r_id);
      $('.i-checks').iCheck({
          checkboxClass: 'icheckbox_square-green',
          radioClass: 'iradio_square-green',
      });
      console.log(setter);

     refresh_data(); 
  function refresh_data(){
      $.ajax({
            type: "POST",
            url: "<?php echo base_url($this->session->userdata('forajax').'/view_sched_list'); ?>"+"/"+r_id,
            dataType: 'json',
        success: function(data){
              $('#tbl_ratesEdit').empty();
              var trHTML = '';
                $.each(data, function(i, item) {
                  if (data[i].MIN == 'M'){ min_usg = data[i].usage_qty;
                   var cb_state = 'hover';  var cbd_state = 'hover';
                    if(data[i].mf == 'Y'){ cb_state = 'checked'; cbd_state = 'checked'; }
                    else if(data[i].mf == 'X'){cb_state = 'hover'; cbd_state = 'checked';}
                  trHTML += '<tr><input id="rate_line_id" type="hidden" value="'+ data[i].line_id +'"><td>' + data[i].charge_name + '</td><td id="desc" text-align:left;>' + data[i].description + '</td><td id="usage" text-align:right;>' + data[i].usage_qty + '</td><td id="rate_v" text-align:right;>' + data[i].rate + '</td><td style="text-align:center; padding-left:5px;" id="min_check"><div id="div_box" style="cursor:default;" class="state icheckbox_square-green '+cb_state+'"></div><div id="div_box_df" style="cursor:default;" class="state icheckbox_square-green '+cbd_state+'"></div></td><td id="action_btn" style="margin:0px;padding:0px;"><a style="width:100%;" id="to_edit" class="btn btn-outline btn-info edit_r" id="gana"><i id="e_rate_icon" class="fa fa-paste success"></i></a></td></tr>';
                  }else{
                  trHTML += '<tr><input id="rate_line_id" type="hidden" value="'+ data[i].line_id +'"><td>' + data[i].charge_name + '</td><td id="desc" text-align:left;>' + data[i].description + '</td><td id="usage" text-align:right;>' + data[i].usage_qty + '</td><td id="rate_v" text-align:right;>' + data[i].rate + '</td><td style="text-align:center; padding-left:5px;" id=""></td><td id="action_btn" style="margin:0px;padding:0px;"><a style="width:100%;" id="to_edit" class="btn btn-outline btn-info edit_r" id="gana"><i id="e_rate_icon" class="fa fa-paste success"></i></a></td></tr>';
                  }
                });
                  $('#tbl_ratesEdit').append(trHTML);
                }      
            });
  }


      $('#edit_rates_form').validate({
        rules :{
            edit_rate_name:{
                required: true
            }
        },submitHandler: function(form){
           dataString = $("#edit_rates_form").serialize();
          $.ajax({
            type: "POST",
            url: "<?php echo base_url($this->session->userdata('forajax').'/update_rate'); ?>",
            data: dataString,
            dataType: 'json',
          success: function(data){
            if(data[0].error == 1){
                notifymsg("danger",data[0].msg);
            }else{
                notifymsg("success",". . .Rate Updated Successfully");
                close_edit(); active_search();
            }
          }      
         }); 
        }
      });

    $(document).on('click','.btn.btn-outline.btn-info.edit_r',function(){
      alert('a');
              if(setter == 0){
                current_usage = $(this).closest('tr').children('#usage').html();
                current_rate = $(this).closest('tr').children('#rate_v').html();
                $(this).closest('tr').children('#usage , #rate_v').html(''); 
                min_box = $(this).closest('tr').find('#div_box');
                min_box_df = $(this).closest('tr').find('#div_box_df');
                $(this).closest('tr').find('#min_check').html('');
                $(this).closest('tr').children('#usage').append('<input style="width:100%;" class="form-control-custom" type="number"  id="iu" name="inline_usage" value="'+current_usage+'">');
                $(this).closest('tr').children('#rate_v').append('<input style="width:100%;" class="form-control-custom" type="number" id="ir" name="inline_rate" value="'+current_rate+'">');
                 
                            if(min_box.hasClass('state icheckbox_square-green checked') ){
                              console.log('asda')
                                $(this).closest('tr').find('#min_check').html('<input  type="checkbox" id="min_chkbox" name="m_opt_ena" value="ok" class="i-checks" checked>');$('#min_chkbox').iCheck('update');
                              }else{
                                $(this).closest('tr').find('#min_check').html('<input  type="checkbox" id="min_chkbox" name="m_opt_ena" value="ok" class="i-checks">');$('#min_chkbox').iCheck('update');
                              }
                            if(min_box_df.hasClass('state icheckbox_square-green checked') ){
                              console.log('asda')
                                $(this).closest('tr').find('#min_check').append('<input  type="checkbox" id="min_chkbox_df" name="m_opt_ena" value="ok" class="i-checks" checked>');$('#min_chkbox').iCheck('update');
                              }else{
                                $(this).closest('tr').find('#min_check').append('<input  type="checkbox" id="min_chkbox_df" name="m_opt_ena" value="ok" class="i-checks">');$('#min_chkbox').iCheck('update');
                              }  
                $(this).closest('tr').children('#action_btn').append('<a id="cancel_edit" class = "btn btn-outline btn-warning cancel"><i class="fa fa-undo success"></i></a><a id="save_edit" class = "btn btn-outline btn-info save"><i class="fa fa-check success"></i></a>')
                $(this).closest('tr').children('#usage , #rate_v').css({"margin":0 , "padding":0});
                $(this).remove();
                setter = 1;
                }else{
                  swal({
                      title: "Sorry!",
                      text: "You still have inline edit , finish it first. ",
                      type: "warning"
                  });
                } 
                  
          });

    $(this).on('click','.btn.btn-outline.btn-warning.cancel',function(){
                $(this).closest('tr').find('#iu , #ir').remove();
                $(this).closest('tr').children('#action_btn').append('<a style="width:100%;" id="to_edit" class="btn btn-outline btn-info edit_r" id="gana"><i id="e_rate_icon" class="fa fa-paste success"></i></a>');
                $(this).closest('tr').find('#min_check').html(min_box).append(min_box_df);
                $(this).closest('tr').children('#usage').html(current_usage);
                $(this).closest('tr').children('#rate_v').html(current_rate);
                $(this).closest('tr').children('#usage , #rate_v').css({"padding":8});
                $(this).closest('tr').find('#cancel_edit , #save_edit').remove();
                setter = 0;
                
      });

    $(document).on('click','.btn.btn-outline.btn-info.save',function(){
      if($('#iu').val() != "" && $('#ir').val() != ""){
        var same = $(this); var to_db = 'no'; var todb_df = 'no';
        var check_box = $(this).closest('tr').find('#min_chkbox').is(":checked");
        var check_box_df = $(this).closest('tr').find('#min_chkbox_df').is(":checked");
          if(check_box == true){to_db = 'yes';}
          if(check_box_df == true){todb_df = 'yes';}
        var rate_ids = $('#edit_rate_id').val();
        var usage_new = $(this).closest('tr').find('#iu').val();
        var rate_new  = $(this).closest('tr').find('#ir').val();
        var line_id    = $(this).closest('tr').children('#rate_line_id').val();
        $.ajax({
                  type: "POST",
                  url: "<?php echo base_url($this->session->userdata('forajax').'/update_inline_sched'); ?>",
                  data: {"rate": rate_new ,"usage": usage_new , "line-id": line_id , "min_flag": to_db , "mindf_flag": todb_df ,"rates_id": rate_ids},
                  dataType: 'json',
              success: function(data){ 
                      if(data[0].error == 1){
                          notifymsg("danger",data[0].msg); 
                        }else{
                          notifymsg("success",". . .Data Updated");
                          $(same).closest('tr').find('#iu , #ir').remove();
                          $(same).closest('tr').children('#action_btn').append('<a style="width:100%;" id="to_edit" class="btn btn-outline btn-info edit_r" id="gana"><i id="e_rate_icon" class="fa fa-paste success"></i></a>');
                          $(same).closest('tr').children('#usage').html(usage_new);
                          $(same).closest('tr').children('#rate_v').html(rate_new);
                          if(check_box == true){
                            $(same).closest('tr').find('#min_check').html('<div id="div_box" style="cursor:default;" class="state icheckbox_square-green checked"></div>');
                          }else{
                            $(same).closest('tr').find('#min_check').html('<div id="div_box" style="cursor:default;" class="state icheckbox_square-green hover"></div>');
                          }
                          if(usage_new < min_usg && min_usg != 0){
                            refresh_data();
                          }
                          $(same).closest('tr').children('#usage , #rate_v').css({"padding":8});
                          $(same).closest('tr').find('#cancel_edit , #save_edit').remove();
                          setter = 0;
                        }
                        refresh_data();
                      }      
                  });
      }
      });
  
      $("#e_sequence-form").validate({
                rules:{
                  seq_num: {
                      required: true,
                      number: true
                  },
                  list_code: {
                      required: true
                  },
                  list_opt: {
                      required: true
                  }
                },
                submitHandler: function(form){
                    $.ajax({
                        type: "POST",
                        url: "<?php echo base_url($this->session->userdata('forajax').'/insert_charge_list_seq'); ?>",
                        data: $('#e_sequence-form').serialize(),
                        dataType: 'json',
                    success: function(data){
                        console.log(data);
                        if(data[0].error == 1){
                            notifymsg("danger",data[0].msg);
                        }else{
                        $('#tbodydaw').empty();
                         console.log("there should be a notification");
                        var trHTML = '';
                        notifymsg("success",". . .List Added Successfully");
                        $.each(data, function(i, item) {
                          trHTML += '<tr><input id="line_id" type="hidden" value="'+ data[i].line_id +'"><input id="list_id" type="hidden" value="'+ data[i].list_id +'"><td style="margin:0px;padding:0px;text-align:right;"><input style="width:100%;" class="form-control" id="id_seq" type="hidden" value="'+ data[i].seq_num +'"><span id="d_span" style="margin-right:30px;">' + data[i].seq_num + '</span></td><td>' + data[i].charge_name + '</td><td>' + data[i].option_name + '</td><td>' + data[i].option_value + '</td><td style="margin:0px;padding:0px;"><a class="btn btn-outline btn-danger del" id="ok_x"><i id="del_icon" class="fa fa-times success"></i></a><a id="ok_e" class="btn btn-outline btn-info edit_l" id="gana"><i id="i_icon" class="fa fa-paste success"></i></a></td></tr>';
                          });
                        $('#tbodydaw').append(trHTML);
                        $("#e_list_chg_code").val("").trigger("chosen:updated");
                        $("#e_list_chg_opt").empty().trigger("chosen:updated");
                        $('#e_sequence-form')[0].reset();
                          }
                      }
                    });
                 }
          });  

      $('#edit_rate_list_form').validate({
        rules :{
            edit_r_desc:{
                required: true
            },
            edit_r_rate:{
                required: true,
                number: true
            },
            edit_r_usage:{
              required: true,
              number : true
            }
        },submitHandler: function(form){
          dataString = $("#edit_rate_list_form").serialize();
          $.ajax({
            type: "POST",
            url: "<?php echo base_url($this->session->userdata('forajax').'/update_rate_sched'); ?>",
            data: dataString,
            dataType: 'json',
          success: function(data){
            if(data[0].error == 1){
                notifymsg("danger",data[0].msg);
            }else{
                notifymsg("success",". . .Schedule Line Updated Successfully");
                refresh_data();
            }   
          }   
         });   
        }
      });



        function alert_cancel(){
            if($('#edit_rates_form').serialize()!=$('#edit_rates_form').data('serialize')){
                swal({
                    title: "Are you sure?",
                    text: "Your work will not be save",
                    type: "warning",
                    showCancelButton: true,
                    confirmButtonColor: "#DD6B55",
                    confirmButtonText: "Leave",
                    cancelButtonText: "Stay",
                    closeOnConfirm: true,
                    closeOnCancel: true },
                function (isConfirm) {
                    if (isConfirm) {
                        close_edit(); active_search();
                        notifymsg("hide","hide");setter = 0;
                    } else {
                        swal("Cancelled");
                    }
                });
                }else{
                close_edit(); active_search();
                notifymsg("hide","hide");setter = 0;
            }
        } 
        $('#cancel_edit').click(function () {
            alert_cancel();
         });
        $('#editX').click(function(){
            alert_cancel();        
       });

});
</script>